package com.neteast.video.activity;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import com.neteast.video.GlobalConstant;
import com.neteast.video.service.DownLoadService;
import com.neteast.video.view.VideoWebView;
import com.neteast.video.view.VideoWebView.LoadStateListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private VideoWebView mWebView;
	private Dialog mExitDialog;
	private String oldUrl=null;
	private SharedPreferences mSP;
	private String url;
	private String fileName;
	
//	public static final String IP="http://218.108.168.7:8790/";
	public static final String IP="http://218.108.85.59:8790/";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        refreshUploadInfo("http://218.108.168.46:8888/onlinevideo/upgrade.xml");
    }
	protected static final int NEED_UPGRADE = 0;
	protected static final int DO_NOT_NEED_UPGRADE = 1;
	protected static final int UPGRADE_ERROR= 2;
	protected static final int PLAY_MP4 = 3;
	UpgradeInfo info = null;	
	
	static class UpgradeInfo{
		public int code;
		public String description;
		public int versioncode;
		public String url;
		public boolean must;
		public long size;
	}
	
	private void refreshUploadInfo(final String path){
		new Thread(new Runnable() {
			public void run() {
				try {
					URL url=new URL(path);
					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(url.openStream(), "UTF-8");
					int event = parser.getEventType();
					while(event!=XmlPullParser.END_DOCUMENT){
						switch (event) {
						case XmlPullParser.START_DOCUMENT:
							info=new UpgradeInfo();
							break;
						case XmlPullParser.START_TAG:
							String tag = parser.getName();
							if ("code".equals(tag)){
								info.code=Integer.parseInt(parser.nextText());
							}else if("description".equals(tag)){
								info.description=parser.nextText();
							}else if("versioncode".equals(tag)){
								info.versioncode=Integer.parseInt(parser.nextText());
							}else if("url".equals(tag)){
								info.url=parser.nextText();
							}else if("must".equals(tag)){
								int b=Integer.parseInt(parser.nextText());
								info.must=b==1;
							}else if("size".equals(tag)) {
								info.size=Long.parseLong(parser.nextText());
							}
							break;
						}
						event=parser.next();
					}
					if (shouldUpload(info.versioncode)) {
						handler.sendEmptyMessage(NEED_UPGRADE);
					}else {
						handler.sendEmptyMessage(DO_NOT_NEED_UPGRADE);
					}
				} catch (Exception e) {
					Log.i("test", "get Upgrade info error",e);
					handler.sendEmptyMessage(UPGRADE_ERROR);
				}
			}
		}).start();
	}
	
	private boolean shouldUpload(int remoteVersioncode) throws NameNotFoundException {
		int localVersionCode=getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
		return remoteVersioncode>localVersionCode;
	}
	
	private void showAppUploadWindow() {
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle("版本升级");
		builder.setCancelable(false);
		builder.setMessage(info.description);
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				startDownLoadService();
				dialog.dismiss();
				finish();
			}
		});
		if (!info.must) {
			builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					init();
					dialog.dismiss();
				}
			});
		}
		builder.create().show();
	}
	
	private void startDownLoadService() {
		Intent intent=new Intent(this, DownLoadService.class);
		intent.putExtra("apk_url", info.url);
		intent.putExtra("size", info.size);
		startService(intent);
	}
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NEED_UPGRADE:
				showAppUploadWindow();
				break;
			case DO_NOT_NEED_UPGRADE:
				init();
				break;
			case UPGRADE_ERROR:
				if (info!=null&&info.must) {
					finish();
				}else {
					Toast.makeText(MainActivity.this, "获取升级信息失败", Toast.LENGTH_SHORT).show();
					init();
				}
				break;
			case PLAY_MP4:
				playMp4();
				break;
			}
		}
	};

	private void init() {
		mSP=getSharedPreferences("videoConfig",Context.MODE_PRIVATE);
		Bundle bundle = getIntent().getExtras();
		if (bundle!=null) {
			url = bundle.getString("url");
			fileName = bundle.getString("fileName");
		}
		initURL();
		initWebView();
		aboutDialog = new AlertDialog.Builder(this)
				.setCancelable(false)
				.setTitle("关于")
				.setMessage("当前版本为："+getVersionName())
				.setNegativeButton("确定", new android.content.DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}})
				.create();
		registerForContextMenu(mWebView);
	}
	private String getVersionName() {
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void initURL() {
		oldUrl=mSP.getString("url",IP );
	}

	ProgressDialog mpDialog;
	private AlertDialog aboutDialog;
	private void initWebView() {
		mWebView = new VideoWebView(this);
		mWebView.loadUrl(oldUrl);
		setContentView(mWebView);
		mWebView.setLoadStateListener(new LoadStateListener() {
			@Override
			public void loadsuccessful(int progress) {
				if (100==progress) {
					handler.sendEmptyMessage(PLAY_MP4);
                    }
                }                
		});
	}
	
	private void playMp4(){
		if (url!=null&&!TextUtils.isEmpty(url.trim())) {
			mWebView.loadUrl("javascript:playMp4('"+url+"','"+fileName+"')");
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			mWebView.loadUrl("javascript:goBackDetail()");
			mWebView.loadUrl("javascript:$.ui.goBack()");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, GlobalConstant.MENU_SET_URL, 0, "设置");
		menu.add(0, GlobalConstant.MENU_CLEAR_MEMORY, 0, "清空缓存");
		menu.add(0, GlobalConstant.MENU_RESET_URL, 0, "初试化链接");
		menu.add(0, GlobalConstant.MENU_ABOUT, 0, "关于");
	}
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);
		switch (item.getItemId()) {
		case GlobalConstant.MENU_SET_URL:
			Intent intent=new Intent(this, SettingActivity.class);
			startActivityForResult(intent, GlobalConstant.ACTIVITY_REQUESTCODE_SETURL);
			break;
		case GlobalConstant.MENU_CLEAR_MEMORY:
			if (mWebView!=null) {
				mWebView.clearCache(true);
				mWebView.clearHistory();
				Toast.makeText(this, "缓存已清空", Toast.LENGTH_SHORT).show();
			}
			break;
		case GlobalConstant.MENU_RESET_URL:
			Editor editor = mSP.edit();
			editor.putString("url", IP);
			editor.commit();
			Toast.makeText(this, "链接已经初始化为 "+IP, Toast.LENGTH_SHORT).show();
			break;
		case GlobalConstant.MENU_ABOUT:
			aboutDialog.show();
			break;
		}
		return true;
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		
		switch (id) {
		case GlobalConstant.MAIN_DIALOG_EXIT:
			return createExitDialog();
		}
		return super.onCreateDialog(id, args);
	}
	/**
	 * 确认是否退出当前应用的对话框
	 * @return
	 */
	private Dialog createExitDialog() {
		AlertDialog.Builder builder=new Builder(this);
		builder.setTitle("真的要退出当前应用吗？")
				.setCancelable(false)
				.setPositiveButton("确定", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						//System.exit(0);
						finish();
						mExitDialog.dismiss();
					}
				})
				.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mExitDialog.dismiss();
					}
				});
		mExitDialog=builder.create();
		mExitDialog.show();
		return mExitDialog;
	}
	/**
	 * ACTIVITY_REQUESTCODE_SETURL  在SettingActivity中重新设置url并返回
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode==GlobalConstant.ACTIVITY_REQUESTCODE_SETURL&&resultCode==RESULT_OK) {
			String newUrl = mSP.getString("url", IP);
			if (!newUrl.equals(oldUrl)) {
				mWebView.loadUrl(newUrl);
				oldUrl=newUrl;
			}
		}
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Bundle bundle = getIntent().getExtras();
		if (bundle!=null) {
			url = bundle.getString("url");
			fileName = bundle.getString("fileName");
			playMp4();
		}
	}
}